﻿import {type NewTaskData} from './task/task.model';
import {Injectable} from '@angular/core';

@Injectable({providedIn:'root'})
export class TasksService{
  private tasks = [
    {
      id:'t1',
      userId:'u1',
      title:'Master Angular-01',
      summary:'Learn all the basic and advanced features of Angular',
      dueDate:'2025-01-30'
    },
    {
      id:'t2',
      userId:'u2',
      title:'Master Angular-02',
      summary:'Learn all the basic and advanced features of Angular',
      dueDate:'2025-02-30'
    },{
      id:'t3',
      userId:'u3',
      title:'Master Angular-03',
      summary:'Learn all the basic and advanced features of Angular',
      dueDate:'2025-03-30'
    }
  ];

  constructor() {
    const tasks = localStorage.getItem('tasks');

    if(tasks){
      this.tasks = JSON.parse(tasks);
    }
  }

  getUserTasks(userId:string){
    return this.tasks.filter((task)=>task.userId === userId);
  }

  addTask(taskDate:NewTaskData,userId:string){
    this.tasks.unshift({
      id:new Date().getTime().toString(),
      userId: userId,
      title:taskDate.title,
      summary: taskDate.summary,
      dueDate: taskDate.date
    });
    this.saveTasks();
  }

  removeTask(id:string){
    this.tasks = this.tasks.filter((task)=> task.id !== id);
    this.saveTasks();
  }

  private saveTasks(){
    localStorage.setItem('tasks',JSON.stringify(this.tasks));
  }
}
